//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;
        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}


document.addEventListener('DOMContentLoaded', function () {
    // 导航切换逻辑
    const navItems = document.querySelectorAll('.nav__item');
    const passwordChangeContainer = document.querySelector('.password-change-container');
    const accountDie = document.querySelector('.die');

    navItems.forEach((item) => {
        item.addEventListener('click', () => {
            navItems.forEach((li) => {
                li.classList.remove('active');
            });
            item.classList.add('active');

            if (item.textContent === '安全管理') {
                passwordChangeContainer.style.display = 'block';
                accountDie.style.display = 'none';
            } else if (item.textContent === '账号注销') {
                passwordChangeContainer.style.display = 'none';
                accountDie.style.display = 'block';
            }
        });
    });

    // 倒计时函数
    // 倒计时函数
    function startCountdown(time) {
        const emailconfirmBtn = document.getElementById('email-confirm-btn');
        if (emailconfirmBtn) {
            emailconfirmBtn.disabled = true;
            countdownTimer = setInterval(() => {
                if (time > 0) {
                    emailconfirmBtn.textContent = `${time}s后重试`;
                    time--;
                } else {
                    clearInterval(countdownTimer);
                    emailconfirmBtn.disabled = false;
                    emailconfirmBtn.textContent = '确定';
                    countdownTimer = null;
                }
            }, 1000);
        }
    }

    const emailconfirmBtn = document.getElementById('email-confirm-btn');
    let timer;

    // 邮箱验证按钮点击事件
    emailconfirmBtn.addEventListener('click', function () {
        const emailDiv = document.querySelector('.emil');
        const email = emailDiv ? emailDiv.textContent : '';
        const encodedEmail = encodeURIComponent(email);
        const data = {
            email: email,
            type: 0
        };
        console.log('发送验证码请求数据:', data);
        $.ajax({
            url: `http://localhost:8080/updatePassword/sendCode?email=${encodedEmail}`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (rsponse) {
                showCustomAlert('验证码已发送，请查收',3000);
                startCountdown(60);
            },
            error: function (error) {
                showCustomAlert('请求出错，请稍后重试。错误信息：' + JSON.stringify(error),3000);
            }
        });
    });

    const emailVerifyBtn = document.getElementById('email-verify-btn');
    const confirmBtn = document.getElementById('confirm-btn');
    const emailVerification = document.getElementById('email-verification');
    const passwordChange = document.getElementById('password-change');
    const successMessage = document.getElementById('success-message');
    const step1 = document.getElementById('step1');
    const step2 = document.getElementById('step2');
    const step3 = document.getElementById('step3');
    // 获取第一步相关元素（虽然初始已有颜色，但仍获取以便后续移除类名操作 ）
    const step1Icon = document.querySelector('.step1-icon');
    const step1Dots = document.querySelectorAll('.step1-dots');
    // 获取第二步相关元素
    const step2Icon = document.querySelector('.step2-icon');
    const step2Dots = document.querySelectorAll('.step2-dots');
    // 获取第三步相关元素
    const step3Icon = document.querySelector('.step3-icon');
    const step3Dots = document.querySelectorAll('.step3-dots');
    const code = document.getElementById('email-code').value;
    emailVerifyBtn.addEventListener('click', function () {
        const code = document.getElementById('email-code').value;
        console.log('输入的验证码:', code);// 从输入框获取值
        $.ajax({
            url: 'http://localhost:8080/updatePassword/verify',
            method: 'POST',
            data: {code: code}, // 这里的第二个code使用上面获取到的值
            success: function (response) {
                console.log('服务器响应:', response);
                if (response && response.success) {
                    step1.classList.add('completed');
                    step2.classList.add('active');
                    emailVerification.style.display = 'none';
                    passwordChange.style.display = 'block';
                    step2Icon.classList.add('active');
                    step2Dots.forEach(dot => dot.classList.add('active'));
                } else {
                    showCustomAlert('验证未成功，可能是后端返回数据异常',3000);
                }
            },
            error: function (error) {
                showCustomAlert('请求出错，请稍后重试',3000);
                console.error('错误详情:', error);
            }
        });
    });
    // 确认修改密码
    $('#confirm-btn').click(function () {
        const newPassword = $('#new-password').val();
        const confirmPassword = $('#confirm-password').val();
        if (newPassword !== confirmPassword) {
            showCustomAlert('两次输入的密码不一致，请重新输入',3000);
            return;
        }
        if (!isValidPassword(newPassword)) {
            showCustomAlert('密码格式不正确，请输入8~20位字母、数字或字符，至少包含两种',3000);
            return;
        }
        const email = $('.emil').text().trim();
        const code = document.getElementById('email-code').value;
        const url = `http://localhost:8080/updatePassword/update?code=${encodeURIComponent(code)}&newPassword=${encodeURIComponent(newPassword)}`;
        $.ajax({
            url: url, // 假设修改密码的接口
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({email: email, newPassword: newPassword}),
            success: function (response) {
                if (response.success) {
                    step2.classList.add('completed');
                    step3.classList.add('active');
                    step2Icon.classList.add('active');
                    step2Dots.forEach(dot => dot.classList.add('active'));
                    step3Icon.classList.add('active');
                    step3Dots.forEach(dot => dot.classList.add('active'));
                    passwordChange.style.display = 'none';
                    successMessage.style.display = 'block';
                    // 5秒后返回邮箱验证步骤
                    setTimeout(() => {
                        step1.classList.remove('completed');
                        step2.classList.remove('active', 'completed');
                        step3.classList.remove('active');
                        emailVerification.style.display = 'block';
                        successMessage.style.display = 'none';
                        // 移除所有步骤图标的 active 类名
                        step1Icon.classList.remove('active');
                        step2Icon.classList.remove('active');
                        step3Icon.classList.remove('active');
                        // 移除所有步骤 ..... 的 active 类名
                        step1Dots.forEach(dot => dot.classList.remove('active'));
                        step2Dots.forEach(dot => dot.classList.remove('active'));
                        step3Dots.forEach(dot => dot.classList.remove('active'));
                        const emailCodeInput = document.getElementById('email-code');
                        const newPasswordInput = document.getElementById('new-password');
                        const confirmPasswordInput = document.getElementById('confirm-password');
                        emailCodeInput.value = '';
                        newPasswordInput.value = '';
                        confirmPasswordInput.value = '';
                    }, 5000);
                } else {
                    showCustomAlert(error,3000);
                }
            },
            error: function (error) {
                showCustomAlert('修改密码失败，请稍后重试');
                console.error('请求出错:', error);
            }
        });
    });
    // 验证密码格式
    function isValidPassword(password) {
        const pattern = /^(?![a-zA-Z]+$)(?![0-9]+$)(?![!@#$%^&*(),.?":{}|<>]+$)[A-Za-z0-9!@#$%^&*(),.?":{}|<>]{8,20}$/;
        return pattern.test(password);
    }

/// 修改邮箱地址
    const modifyEmailBtn = document.querySelector('#modifyEmailBtn');
// 获取修改按钮
    const closeEmailPopup = document.getElementById('closeEmailPopup');
// 这里原代码中 HTML 没有 id 为 email-address 的元素，推测是多余代码，先注释掉
    const emailaddress = document.getElementById('email-address');
    const emailPopup = document.getElementById('emailPopup'); // 修正 ID 大小写

// 点击修改按钮，显示邮箱绑定弹窗
    if (modifyEmailBtn) {
        modifyEmailBtn.addEventListener('click', function () {
            if (emailPopup) {
                emailPopup.style.display = 'block';
                emailaddress.style.display = 'none';
            }
        });
    }
//注销
    const bindEmailBtn=document.getElementById('bindEmailBtn');
    const accountElement = document.querySelector('.accout-die');
    const userId = accountElement.dataset.userId;
    bindEmailBtn.addEventListener('click', function () {
        // 弹出二次确认框
        confirms('您确定要永久注销账号吗？此操作无法恢复！请慎重考虑', (isConfirmed) => {
            if (isConfirmed) {
                // 发送注销请求
                console.log(21231)
                $.ajax({
                    url: '/writeOff',
                    type: 'POST',
                    data: { userId: userId },
                    success: function(response) {
                        console.log(response)
                        if (response.success) {
                            showCustomAlert('账号注销成功！', 3000);
                            window.location.href = '/login';
                        } else {
                            showCustomAlert(`注销失败：${response.message}`, 3000);
                        }
                    },
                    error: function(error) {
                        console.error('注销请求失败:', error);
                            showCustomAlert('请求出错，请稍后重试', 3000);
                    }
            });
            }
        })

    });
// 点击关闭按钮
    if (closeEmailPopup) {
        closeEmailPopup.addEventListener('click', function () {
            if (emailPopup) {
                emailPopup.style.display = 'none'; // 隐藏弹窗
            }
        });
    }
    const open1 = document.getElementById('open1');
    const close1 = document.getElementById('close1');
    const newPasswordInput = document.getElementById('new-password');

    const open2 = document.getElementById('open2');
    const close2 = document.getElementById('close2');
    const confirmPasswordInput = document.getElementById('confirm-password');

    open1.addEventListener('click', function () {
        newPasswordInput.type = 'password';
        open1.style.display = 'none';
        close1.style.display = 'block';
    });

    close1.addEventListener('click', function () {
        newPasswordInput.type = 'text';
        open1.style.display = 'block';
        close1.style.display = 'none';
    });

    open2.addEventListener('click', function () {
        confirmPasswordInput.type = 'text';
        confirmPasswordInput.type = 'password';
        open2.style.display = 'none';
        close2.style.display = 'block';
    });

    close2.addEventListener('click', function () {
        confirmPasswordInput.type = 'text';
        open2.style.display = 'block';
        close2.style.display = 'none';
    });
});